package com.example.studentalarm.service;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;

import com.example.studentalarm.R;
import com.example.studentalarm.activity.EditTimetableActivity;
import com.example.studentalarm.activity.MainActivity;
import com.example.studentalarm.bean.AlarmConfigBean;
import com.example.studentalarm.bean.TimetableBean;
import com.example.studentalarm.config.SharedPreferencesUtils;
import com.example.studentalarm.constant.ApiConstant;
import com.example.studentalarm.database.DbManager;
import com.example.studentalarm.utils.LogUtil;
import com.example.studentalarm.utils.SoundConfigUtils;
import com.example.studentalarm.utils.Utils;


/**
 * @author ZHQ
 * @create 2019/10/8
 * @Describe 闹钟告警广播接收器
 */
public class AlarmReceiver extends BroadcastReceiver {
    public static final String ACTION_ALARM_ALERT = "com.example.studentTimetable.happened.alarm";
    public static final String ACTION_NOTIFICATION_OPENED = "com.example.studentTimetable.onclick.alarm.message";
    public static final String channel_id = "channel_1";
    public static final String channel_name = "channel_name_1";

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        LogUtil.e("AlarmReceiver.....:" + action);
        if (ACTION_ALARM_ALERT.equals(action)) {
            // 播放音乐  测试默认 响铃+振动
            //此处接收闹钟时间发送过来的广播信息，为了方便设置提醒内容
            int alarmId = intent.getIntExtra("alarmId", 1);
            LogUtil.e("闹钟响了...." + "alarmId:" + alarmId);
            String title = intent.getStringExtra("title");
            String content = intent.getStringExtra("content");
            TimetableBean alarmBean = DbManager.getInstance().queryTimetableById(alarmId);
            if (alarmBean.getAlarmState() == ApiConstant.AlarmState.UNSEND) {
                showNormal(context, alarmId, title, content);
//                //回调Service,同一个Service只会启动一个，所以直接再次启动Service，会重置开启新的提醒，重复提醒，当用户点击通知栏取消重复提醒
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                intent.setPackage("com.example.studentalarm");
//                intent.setClass(context, AlarmService.class);
//                //对8.0系统兼容问题处理，服务放置前台服务
//                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                    context.startForegroundService(intent);
//                } else {
//                    context.startService(intent);
//                }
            }
        } else if (ACTION_NOTIFICATION_OPENED.equals(action)) {
            LogUtil.e("点击通知....");
            // 停止播放音乐
            SoundConfigUtils.getInstance(context).stopSound();
            Bundle bundle = intent.getExtras();
            Integer id = bundle.getInt("id");
            if (Utils.isExistMainActivity(MainActivity.class, context)) {
                DbManager.getInstance().updateAlarmState(id, ApiConstant.AlarmState.SEND);//处理重复提醒闹钟
                //取消闹钟
                cancelAlarm(context, id);
                //跳转到课程表详情
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setClass(context, EditTimetableActivity.class);
                intent.putExtras(bundle);
                context.startActivity(intent);
            } else {
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setClass(context, MainActivity.class);
                intent.setAction(ACTION_NOTIFICATION_OPENED);
                intent.putExtras(bundle);
                context.startActivity(intent);
            }

        }

    }

    /***
     * 取消闹钟
     * @param mContext
     * @param alarmId
     */
    public void cancelAlarm(Context mContext, Integer alarmId) {
        Intent intent = new Intent(mContext, AlarmReceiver.class);
        PendingIntent pi = PendingIntent.getBroadcast(mContext, alarmId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pi);
    }

    /***
     * 显示通知栏
     * @param title
     * @param content
     */
    private void showNormal(Context context, int alarmId, String title, String content) {
        AlarmConfigBean configBean = SharedPreferencesUtils.getInstance(context).getAlarmConfigBean();
        LogUtil.e("铃声状态：" + configBean.isMusic() + "  振动状态：" + configBean.isVibration());
        SoundConfigUtils.getInstance(context).startSound(configBean.getRingerMode());
        Intent intent = new Intent(context, AlarmReceiver.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.setAction(ACTION_NOTIFICATION_OPENED);
        Bundle bundle = new Bundle();
        bundle.putInt("id", alarmId);
        intent.putExtras(bundle);
        PendingIntent pi = PendingIntent.getBroadcast(context, alarmId, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        int alarmResponse = Notification.DEFAULT_VIBRATE;
//        if (configBean.isMusic()) {
//            alarmResponse = Notification.DEFAULT_SOUND;
//        }
//        if (configBean.isVibration()) {
//            alarmResponse = Notification.DEFAULT_VIBRATE;
//        }
//        if (configBean.isMusic() && configBean.isVibration()) {
//            alarmResponse = Notification.DEFAULT_ALL;
//        }
        if (Build.VERSION.SDK_INT >= 26) {
            NotificationChannel channel = new NotificationChannel(channel_id, channel_name,NotificationManager.IMPORTANCE_HIGH);
            manager.createNotificationChannel(channel);
            Notification notificationChannel = new Notification.Builder(context, channel_id)
                    .setContentTitle(title)
                    .setContentText(content)
                    .setSmallIcon(R.mipmap.app_logo)
                    .setAutoCancel(true)
                    .setContentInfo("上课提醒")
                    .setContentIntent(pi)
                    .build();
           manager.notify(alarmId, notificationChannel);
        } else {
            Notification notification = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.app_logo)     //设置通知图标。
                    .setTicker(content)        //通知时在状态栏显示的通知内容
                    .setContentInfo("上课提醒")        //内容信息
                    .setContentTitle(title)        //设置通知标题。
                    .setContentText(content)        //设置通知内容。
                    .setAutoCancel(true)                //点击通知后通知消失
                    .setContentIntent(pi)    //.setDefaults(alarmResponse)        //设置系统默认的通知音乐、振动、LED等。
                    .build();
            manager.notify(alarmId, notification);
        }
    }
}
